﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Collections.Specialized;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Active.Core;
namespace Active.Controls
{
    /// <summary>
    /// BalanceBill 的摘要说明
    /// </summary>
    public class BalanceBill : Control
    {
        #region Properties
        private string _CssClass = "";
        /// <summary>
        /// 样式
        /// </summary>
        public string CssClass
        {
            get { return _CssClass; }
            set { _CssClass = value; }
        }

        private Bill _CurrentBill = null;
        /// <summary>
        /// 当前Bill
        /// </summary>
        public Bill CurrentBill
        {
            get
            {
                if (_CurrentBill == null)
                {
                    _CurrentBill = GetBill();
                }
                return _CurrentBill;
            }
        }

        private Orders _CurrentOrders;
        /// <summary>
        /// 当前Bill的所以Orders
        /// </summary>
        private Orders CurrentOrders
        {
            get
            {
                if (CurrentBill == null)
                    return null;
                return CurrentBill.Orders; ;
            }
        }

        private decimal _TotalBrokerage = 0;
        /// <summary>
        /// 订单所用的返点数
        /// </summary>
        private decimal TotalBrokerage
        {
            get { return _TotalBrokerage; }
            set { _TotalBrokerage = value; }
        }

        private int _MainRowsCount = CompanySettings.Instance.BalanceBillMainRows;
        /// <summary>
        /// 客户订单行数
        /// </summary>
        public int MainRowsCount
        {
            get { return _MainRowsCount; }
        }

        private int _BalanceBillRowCount = 0;
        /// <summary>
        /// 平衡表总行数
        /// </summary>
        private int BalanceBillRowCount
        {
            get
            {
                if (_BalanceBillRowCount == 0)
                    _BalanceBillRowCount = GetBalanceBillRowCount(); //需要修改
                return _BalanceBillRowCount;
            }

        }

        private int _PageCount = 0;
        /// <summary>
        /// 总页数
        /// </summary>
        private int PageCount
        {
            get
            {
                if (_PageCount == 0)
                {
                    if (BalanceBillRowCount % MainRowsCount == 0)
                        _PageCount = BalanceBillRowCount / MainRowsCount;
                    else
                        _PageCount = BalanceBillRowCount / MainRowsCount + 1;
                }
                return _PageCount;
            }
        }
        private bool _IsPager = false;
        /// <summary>
        /// 是否分页
        /// </summary>
        public bool IsPager
        {
            get { return _IsPager; }
            set { _IsPager = value; }
        }
        private int ps = 1;
        #endregion

        #region method
        private int GetBalanceBillRowCount()
        {
            int rowCount = 0;
            foreach (Order order in CurrentBill.Orders)
            {
                foreach (CustomerOrder co in order.CustomerOrders)
                {
                    if (co.MediaOrders == null || co.MediaOrders.Count == 0)
                        rowCount++;
                    else
                        foreach (MediaOrder mo in co.MediaOrders)
                        {
                            rowCount++;
                        }
                }
            }
            return rowCount;
        }
        
        protected Bill GetBill()
        {
            string idString;
            if (IsPager)
                idString = Page.Request.QueryString["billId"];
            else
                idString = Page.Request.QueryString["id"];
            object businessObj = Page.Session["CurrentObj"];
            if (businessObj == null || !(businessObj is Bill)
                || (!Page.IsPostBack && !((Bill)businessObj).Id.ToString().Equals(idString)))
            {
                try
                {
                    if (!string.IsNullOrEmpty(idString))
                    {
                        businessObj = Bill.GetBill(int.Parse(idString));
                    }
                    else
                    {
                        businessObj = null;
                    }
                    Page.Session["CurrentObj"] = businessObj;
                }
                catch (System.Security.SecurityException)
                {
                    Page.Response.Redirect("~/Bill");
                }
            }
            return businessObj as Bill;
        }

        /// <summary>
        /// 输出客户Order
        /// </summary>
        /// <param name="order"></param>
        private void RenderCustomerOrder(CustomerOrder customerOrder, HtmlTextWriter writer)
        {
            //单价
            writer.AddAttribute(HtmlTextWriterAttribute.Rowspan,
                customerOrder.MediaOrders.Count > 1 ? customerOrder.MediaOrders.Count.ToString() : "1");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write(Formater.FormatPrice(customerOrder.UnitPrice, customerOrder.Category));
            writer.RenderEndTag();
            //次数
            writer.AddAttribute(HtmlTextWriterAttribute.Rowspan,
                customerOrder.MediaOrders.Count > 1 ? customerOrder.MediaOrders.Count.ToString() : "1");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write(customerOrder.Times.ToString());
            writer.RenderEndTag();
            //实收优惠率
            writer.AddAttribute(HtmlTextWriterAttribute.Rowspan,
                customerOrder.MediaOrders.Count > 1 ? customerOrder.MediaOrders.Count.ToString() : "1");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            double realDiscount = customerOrder.RealDiscount * 100;
            if (customerOrder.Category == OrderType.Additional)
                writer.Write("-");
            else
                writer.Write(realDiscount > 0 ? realDiscount.ToString() + "%" : "-");
            writer.RenderEndTag();
            //实收
            writer.AddAttribute(HtmlTextWriterAttribute.Rowspan,
                customerOrder.MediaOrders.Count > 1 ? customerOrder.MediaOrders.Count.ToString() : "1");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write(Formater.FormatPrice(customerOrder.RealPayout));
            writer.RenderEndTag();
            //应收优惠率
            writer.AddAttribute(HtmlTextWriterAttribute.Rowspan,
                customerOrder.MediaOrders.Count > 1 ? customerOrder.MediaOrders.Count.ToString() : "1");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            double orderDiscount = customerOrder.Discount * 100;
            if (customerOrder.Category == OrderType.Additional)
                writer.Write("-");
            else
                writer.Write(orderDiscount > 0 ? orderDiscount.ToString() + "%" : "-");
            writer.RenderEndTag();
            //应收
            writer.AddAttribute(HtmlTextWriterAttribute.Rowspan,
                customerOrder.MediaOrders.Count > 1 ? customerOrder.MediaOrders.Count.ToString() : "1");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write(Formater.FormatPrice(customerOrder.Payout));
            writer.RenderEndTag();
        }

        /// <summary>
        /// 输出固定列,值
        /// </summary>
        /// <param name="text"></param>
        /// <param name="count"></param>
        private void WriteNull(string text, int count, HtmlTextWriter writer)
        {
            for (int i = 0; i < count; i++)
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                writer.Write(text);
                writer.RenderEndTag();
            }
        }
        /// <summary>
        /// 输出媒体Order
        /// </summary>
        private void RenderMediaOrder(MediaOrder mediaOrder, HtmlTextWriter writer)
        {
            //单价
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write(Formater.FormatPrice(mediaOrder.UnitPrice, mediaOrder.Category));
            writer.RenderEndTag();
            //次数
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write(mediaOrder.Times.ToString());
            writer.RenderEndTag();
            //优惠率
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            double discount = mediaOrder.Discount * 100;
            if (mediaOrder.Category == OrderType.Additional)
                writer.Write("-");
            else
                writer.Write(discount > 0 ? discount.ToString() + "%" : "-");
            writer.RenderEndTag();
            //实付
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write(Formater.FormatPrice(mediaOrder.Payout));
            writer.RenderEndTag();
        }

        /// <summary>
        /// 显示一条订单信息
        /// </summary>
        /// <param name="order"></param>
        /// <param name="writer"></param>
        private void RenderOrder(Order order, HtmlTextWriter writer)
        {
            if (order.CustomerOrders != null && order.CustomerOrders.Count > 0)
            {
                //显示Order
                int maxCount = Math.Max(order.CustomerOrders.Count, order.MediaOrders.Count);
                //int minCount = Math.Min(order.CustomerOrders.Count, order.MediaOrders.Count);
                for (int i = 0; i < order.CustomerOrders.Count; i++)
                {
                    CustomerOrder custOrder = order.CustomerOrders[i];
                    writer.RenderBeginTag(HtmlTextWriterTag.Tr);
                    //媒介和频道名称
                    if (i == 0)
                    {
                        writer.AddAttribute(HtmlTextWriterAttribute.Rowspan, maxCount.ToString());
                        writer.RenderBeginTag(HtmlTextWriterTag.Td);
                        string nameAndChannel = (order.Media.Name == custOrder.Channel) ?
                            custOrder.Channel : order.Media.Name + "<br/>" + custOrder.Channel;
                        writer.Write(nameAndChannel);
                        writer.RenderEndTag();
                    }
                    //显示客户订单
                    RenderCustomerOrder(custOrder, writer);
                    //显示客户部备注
                    if (i == 0)
                    {
                        writer.AddAttribute(HtmlTextWriterAttribute.Class, "left");
                        writer.AddAttribute(HtmlTextWriterAttribute.Rowspan, maxCount.ToString());
                        writer.RenderBeginTag(HtmlTextWriterTag.Td);
                        writer.Write(order.CustomerDescription.Replace(Environment.NewLine,"<br />"));
                        writer.RenderEndTag();
                    }
                    //显示媒介订单
                    if (custOrder.MediaOrders.Count > 0)
                    {
                        RenderMediaOrder(custOrder.MediaOrders[0], writer);
                    }
                    else
                    {
                        WriteNull(" ", 4, writer);
                    }
                    //显示媒介部备注
                    if (i == 0)
                    {
                        writer.AddAttribute(HtmlTextWriterAttribute.Class, "left");
                        writer.AddAttribute(HtmlTextWriterAttribute.Rowspan, maxCount.ToString());
                        writer.RenderBeginTag(HtmlTextWriterTag.Td);
                        if (order.DeductFromAdvance > 0)
                        {
                            string description = "从预存款中冲抵" 
                                + Formater.FormatPrice(order.DeductFromAdvance) 
                                + "<br />剩余" + Formater.FormatMoney(order.Media.Advance);
                            writer.Write(description);
                        }
                        writer.RenderEndTag();
                    }
                    writer.RenderEndTag();

                    for (int j = 1; j < custOrder.MediaOrders.Count; j++)
                    {
                        writer.RenderBeginTag(HtmlTextWriterTag.Tr);
                        RenderMediaOrder(custOrder.MediaOrders[j], writer);
                        writer.RenderEndTag();
                    }
                }
            }
        }

        /// <summary>
        /// WriteTable
        /// </summary>
        /// <param name="Orders"></param>
        /// <param name="pageNo"></param>
        /// <param name="writer"></param>
        private void WriteTable(Orders Orders, HtmlTextWriter writer)
        {
            #region Table

            WriteStartTable(1, writer);

            #region TableBody
            foreach (Order order in Orders)
            {
                RenderOrder(order, writer);
                TotalBrokerage += order.DeductFromBrokerage;
            }
            #endregion

            WriteEndTable(true, PageCount, writer);

            #endregion
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="writer"></param>
        private void WriteStartTable(int pageNo, HtmlTextWriter writer)
        {
            writer.AddAttribute("id", "printDiv" + pageNo.ToString());
            writer.RenderBeginTag(HtmlTextWriterTag.Div);
            if (CssClass != "")
                writer.AddAttribute("class", CssClass);
            else
                writer.AddAttribute("class", "normal");
            writer.AddAttribute("id", "printTable");
            writer.RenderBeginTag(HtmlTextWriterTag.Table);
            #region 第一行
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            //
            writer.AddAttribute("colspan", "13");
            writer.AddAttribute("class", "fontLarger noneborder");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("收支平衡表");
            writer.RenderEndTag();
            //EndRow
            writer.RenderEndTag();

            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            //
            writer.AddAttribute("colspan", "8");
            writer.AddAttribute("class", "noneborder left");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("投放日期： " + CurrentBill.StartDate.Date.ToShortDateString() + "~" + CurrentBill.EndDate.Date.ToShortDateString());
            writer.RenderEndTag();
            //
            writer.AddAttribute("colspan", "4");
            writer.AddAttribute("class", "noneborder left");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("客户： " + CurrentBill.Customer.Name + "<br/>" + "产品:" + CurrentBill.ProductName);
            writer.RenderEndTag();
            //
            writer.AddAttribute("colspan", "1");
            writer.AddAttribute("class", "noneborder left");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("编号:" + CurrentBill.Number + "(" + pageNo.ToString() + "/" + PageCount.ToString() + ")");
            writer.RenderEndTag();
            //EndRow
            writer.RenderEndTag();
            #endregion

            #region 第二行
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            writer.AddAttribute("rowspan", "2");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("媒体");
            writer.RenderEndTag();
            //
            writer.AddAttribute("colspan", "2");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("报价");
            writer.RenderEndTag();
            //
            writer.AddAttribute("colspan", "2");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("实收客户");
            writer.RenderEndTag();
            //
            writer.AddAttribute("colspan", "2");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("应收客户");
            writer.RenderEndTag();
            //
            writer.AddAttribute("rowspan", "2");
            writer.AddAttribute("class", "left");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("客户部备注");
            writer.RenderEndTag();
            //
            writer.AddAttribute("colspan", "2");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("报价");
            writer.RenderEndTag();
            //
            writer.AddAttribute("colspan", "2");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("应付媒介款");
            writer.RenderEndTag();
            //
            writer.AddAttribute("rowspan", "2");
            writer.AddAttribute("class", "left");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("媒介部备注");
            writer.RenderEndTag();
            //EndRow
            writer.RenderEndTag();
            #endregion

            #region 第三行
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            //
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("单价");
            writer.RenderEndTag();
            //
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("次数");
            writer.RenderEndTag();
            //
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("优惠率");
            writer.RenderEndTag();
            //
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("实收");
            writer.RenderEndTag();
            //
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("优惠率");
            writer.RenderEndTag();
            //
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("应收");
            writer.RenderEndTag();
            //
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("单价");
            writer.RenderEndTag();
            //
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("次数");
            writer.RenderEndTag();
            //
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("优惠率");
            writer.RenderEndTag();
            //
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("实付");
            writer.RenderEndTag();
            //EndRow
            writer.RenderEndTag();
            #endregion
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="isWriteTotal"></param>
        /// <param name="writer"></param>
        private void WriteEndTable(bool isWriteTotal, int pageNo, HtmlTextWriter writer)
        {
            #region 合计行...
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            //
            writer.AddAttribute("colspan", "3");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.RenderEndTag();
            //
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("合计:");
            writer.RenderEndTag();
            //
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            if (isWriteTotal)
            {
                writer.Write(Formater.FormatPrice(CurrentBill.RealIncome));
            }
            else
                writer.Write("见最后页");
            writer.RenderEndTag();
            //
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.RenderEndTag();
            //
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            if (isWriteTotal)
            {
                writer.Write(Formater.FormatPrice(CurrentBill.Income));
            }
            else
                writer.Write("见最后页");
            writer.RenderEndTag();
            //
            writer.AddAttribute("colspan", "3");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.RenderEndTag();
            //
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("合计:");
            writer.RenderEndTag();
            //
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            if (isWriteTotal)
            {
                writer.Write(Formater.FormatPrice(CurrentBill.Payout - TotalBrokerage));
            }
            else
                writer.Write("见最后页");
            writer.RenderEndTag();
            //
            writer.AddAttribute("class", "left");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            if (isWriteTotal)
                writer.Write("所用返点数:" + Formater.FormatMoney(TotalBrokerage));
            else
                writer.Write("见最后页");
            writer.RenderEndTag();
            //EndTr
            writer.RenderEndTag();
            #endregion

            #region 签名行
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            //
            writer.AddAttribute("class", "right");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("客户部:");
            writer.RenderEndTag();
            //
            writer.AddAttribute("colspan", "2");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.RenderEndTag();
            //
            writer.AddAttribute("class", "right");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("媒介部:");
            writer.RenderEndTag();
            //
            writer.AddAttribute("colspan", "3");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.RenderEndTag();
            //
            writer.AddAttribute("class", "right");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("执行总监:");
            writer.RenderEndTag();
            //
            writer.AddAttribute("colspan", "5");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.RenderEndTag();
            //EndTr
            writer.RenderEndTag();
            #endregion

            #region 签名行
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            //
            writer.AddAttribute("class", "right");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("客户经理:");
            writer.RenderEndTag();
            //
            writer.AddAttribute("colspan", "2");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.RenderEndTag();
            //
            writer.AddAttribute("class", "right");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("媒介经理:");
            writer.RenderEndTag();
            //
            writer.AddAttribute("colspan", "3");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.RenderEndTag();
            //
            writer.AddAttribute("class", "right");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("总经理:");
            writer.RenderEndTag();
            //
            writer.AddAttribute("colspan", "5");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.RenderEndTag();
            //EndTr
            writer.RenderEndTag();
            #endregion
            //EndTable
            writer.RenderEndTag();
            //EndDiv
            writer.RenderEndTag();
            //打印按钮
            writer.AddAttribute("type", "button");
            writer.AddAttribute("class", "button");
            if (IsPager)
            {
                writer.AddAttribute("value", "打印第" + pageNo.ToString() + "页");
                writer.AddAttribute("onclick", string.Format("javascript:window.open('{0}')", Utils.RelativeWebRoot + "Print.aspx?id=" + "printDiv" + pageNo.ToString()));
            }
            else
            {
                writer.AddAttribute("value", "打   印");
                if (PageCount == 1)
                    writer.AddAttribute("onclick", string.Format("javascript:window.open('{0}')", Utils.RelativeWebRoot + "Print.aspx?id=" + "printDiv" + pageNo.ToString()));
                else if (PageCount > 1)
                {
                    writer.AddAttribute("onclick", string.Format("javascript:window.open('{0}')", Utils.RelativeWebRoot + "PrintPager.aspx?billId=" + CurrentBill.Id.ToString()));
                }
            }
            writer.RenderBeginTag(HtmlTextWriterTag.Input);
            writer.RenderEndTag();
        }
        #endregion

        #region override
        protected override void Render(HtmlTextWriter writer)
        {
            if (CurrentOrders == null || CurrentOrders.Count == 0)
            {
                writer.AddAttribute("style", "color:Red; font-size:x-large;");
                writer.RenderBeginTag(HtmlTextWriterTag.Div);
                if (!IsPager)
                    writer.Write("该清单无任何订单");
                writer.RenderEndTag();
                return;
            }
            WriteTable(CurrentOrders, writer);
        }
        #endregion
    }
}
